package com.tjsinfo.tjsoa.export.bo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.ObjectUtils.Null;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.hibernate.Hibernate;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.jsoup.Jsoup;
import org.springframework.jdbc.core.RowMapper;
//import org.jsoup.nodes.Document;
//import org.jsoup.nodes.Element;
//import org.jsoup.select.Elements;


import com.tjsinfo.tjsoa.Dao.IHibernateDao;
import com.tjsinfo.tjsoa.Dao.IQbcDao;
import com.tjsinfo.tjsoa.Dao.ISpringDao;
import com.tjsinfo.tjsoa.articles.bo.ITArticlesManage;
import com.tjsinfo.tjsoa.articles.bo.TArticlesRolesManage;
import com.tjsinfo.tjsoa.articles.vo.TIndexArticles;
import com.tjsinfo.tjsoa.common.FileManage;
import com.tjsinfo.tjsoa.common.PaginationSupport;
import com.tjsinfo.tjsoa.common.ToolKit;
import com.tjsinfo.tjsoa.documentationflow.dangweifawen.vo.TDangweifawenFujian;
import com.tjsinfo.tjsoa.documentationflow.dangweifawen.vo.TDangweifawenNeirong;
import com.tjsinfo.tjsoa.documentationflow.xingzhengfawen.vo.FaWenInfo;
import com.tjsinfo.tjsoa.documentationflow.xingzhengfawen.vo.TXingzhengfawenFujian;
import com.tjsinfo.tjsoa.documentationflow.xingzhengfawen.vo.TXingzhengfawenNeirong;
import com.tjsinfo.tjsoa.meetingroom.action.newArrangementsAction;
import com.tjsinfo.tjsoa.system.vo.TjsRoles;


public class TExportManageImpl implements IExportManage{
	private IQbcDao qbcDao;
	private IHibernateDao hibernateDao;
	private ISpringDao springDao;
	private TArticlesRolesManage articlesRolesManage;

	private final static String HTML_HEAD = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html><head><meta content=\"text/html; charset=utf-8\" /><title>天津市粮油集团有限公司</title></head><body><div>";
	private final static String HTML_END = "</div></body></html>";
	
	public IHibernateDao getHibernateDao() {
		return hibernateDao;
	}

	public void setHibernateDao(IHibernateDao hibernateDao) {
		this.hibernateDao = hibernateDao;
	}

	public IQbcDao getQbcDao() {
		return qbcDao;
	}

	public void setQbcDao(IQbcDao qbcDao) {
		this.qbcDao = qbcDao;
	}
	
	public TArticlesRolesManage getArticlesRolesManage() {
		return articlesRolesManage;
	}

	public void setArticlesRolesManage(TArticlesRolesManage articlesRolesManage) {
		this.articlesRolesManage = articlesRolesManage;
	}
	
	public ISpringDao getSpringDao() {
		return springDao;
	}

	public void setSpringDao(ISpringDao springDao) {
		this.springDao = springDao;
	}

/**
 * 多个栏目联合查询
 * @param cid
 * @param sstart
 * @param slimit
 * @param date
 * @return
 */
public PaginationSupport findByCids(String cidsString, String sstart,String slimit,Date startDate,Date endDate) {
	
	DetachedCriteria criteria = DetachedCriteria.forClass(TIndexArticles.class); 
	Disjunction disj = Restrictions.disjunction();
	PaginationSupport ps = null;
	if (cidsString!=null & !"".equals(cidsString )){
		String[] cids = cidsString.split(",");
		for (String cid : cids) {
		     disj.add(Restrictions.eq("cid", Integer.valueOf(cid)));
		}
		criteria.add(disj);
		if ( startDate.getTime()>endDate.getTime() ){
			Date tempDate = startDate;
			startDate = endDate;
			endDate = tempDate;
		}
		criteria.add(Restrictions.and(
				Restrictions.sqlRestriction("CAST({alias}.createDate AS DateTime)>=?",startDate,Hibernate.DATE),
				Restrictions.sqlRestriction("CAST({alias}.createDate AS DateTime)<=?",endDate,Hibernate.DATE)));
		List<Order> orderlist = new ArrayList<Order>();
		orderlist.add(Order.desc("id"));
		ps= qbcDao.findPageByCriteria(criteria,orderlist,Integer.parseInt(slimit), Integer.parseInt(sstart));
	}
	return ps;
}

/**
 * 根据ids查找并返回文章列表
 * @param idsArray
 * @return
 */
public List<TIndexArticles> findByIds(String[] idsArray) {
	// TODO Auto-generated method stub
	DetachedCriteria criteria = DetachedCriteria.forClass(TIndexArticles.class); 
	Disjunction disj = Restrictions.disjunction();
	for (String aid : idsArray) {
	     disj.add(Restrictions.eq("id", Integer.valueOf(aid)));
	}
	criteria.add(disj);
	return  (List<TIndexArticles>) qbcDao.getCriteria(criteria);
}

/**
 * 生成文章html
 */
public void createArticlesHtml(TIndexArticles article,
		String fromFilePathString, String toFilePathString, String fujianPathString) {
	
        StringBuffer sb = new  StringBuffer();   
        sb.append(HTML_HEAD);
        sb.append("<h1 style=\"text-align:center; font-size:24px;line-height: 35px;width: 600px; margin: 0 auto;\">");
        sb.append(article.getTitle());
        sb.append("</h1><h2 style=\"font-weight:normal; text-align:center; margin:4px 0 6px 0; font-size:14px\">作者：");
        sb.append(article.getAuthor());
        sb.append("&nbsp;&nbsp;&nbsp;&nbsp;发布时间：");
        sb.append(article.getCreateDate());
        sb.append("<div style=\"width:675px;margin:0 auto;line-height:28px\"><font size=\"4\">");
        
        String articleUuid = article.getUuid();
        //下载content
        sb.append(downloadContent(fromFilePathString +"\\"+ articleUuid+".html")); 
            
        sb.append("</font></div>");
        String fujianString = article.getUploadFile();
        FileManage.newFolder(toFilePathString+"\\"+ articleUuid);
        //如果有附件，将附件链接加入到html中
    	if(fujianString!=null & !"".equals(fujianString)){      
    		org.jsoup.nodes.Document doc = Jsoup.parse(fujianString);
    		org.jsoup.select.Elements urls = doc.select("a[href]");
    		for(org.jsoup.nodes.Element url:urls){
    			String urlString = url.attr("href").replace("/", "\\").trim();
    			String sourceUrl = fujianPathString + urlString;
    			String fileName = urlString.substring(urlString.lastIndexOf("\\")+1);
    			String targetUrl = toFilePathString + "\\" + article.getUuid() + "\\" + fileName;
    			FileManage.copyFile(sourceUrl, targetUrl);
    			sb.append("<div><a href=\"" + fileName + "\">" + fileName + "</a></div>");
    		}
        }
        sb.append(HTML_END);
   
        //上传	
        uploadHtml(toFilePathString+"\\"+ articleUuid + "\\" + articleUuid +".html" ,sb.toString());
}

private String downloadContent(String contentUrl){
	BufferedReader br=null;   
	StringBuffer sbtemp = new  StringBuffer();  
	try { 
	       // 读取正文
        br=new BufferedReader(new InputStreamReader(new FileInputStream(contentUrl),  "UTF-8"));            
        String temp=null;          
        while((temp=br.readLine())!=null){   
        	sbtemp.append(temp);   
        } 
    } catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (UnsupportedEncodingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return sbtemp.toString();
}

private void uploadHtml(String htmlUrl, String htmlString){
    FileOutputStream o;
	try { 
	       // 读取正文
		o = new FileOutputStream(htmlUrl);
		o.write(htmlString.getBytes("UTF-8"));
	    o.close();
    } catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (UnsupportedEncodingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}

/**
 * 创建Articles XML
 */
public void createArticlesXML(List<TIndexArticles> articlesList,	String toFilePathString) {
	
        Document _docsDocument = DocumentHelper.createDocument();
        Element _root = _docsDocument.addElement("documents");
        for(TIndexArticles article : articlesList){
        	Element _docElement = _root.addElement("document");
        	_docElement.addElement("uuid").setText(article.getUuid());
        	
        	_docElement.addElement("type").setText(articlesRolesManage.findById(article.getCid()).getName());
        	_docElement.addElement("biaoti").setText(article.getTitle());
        	_docElement.addElement("zuozhe").setText(article.getAuthor());
        	_docElement.addElement("riqi").setText(article.getCreateDate());
        	Element _fujian = _docElement.addElement("fujian");
        	_fujian.addElement("file").setText(article.getUuid()+".html");
        	String fujianString = article.getUploadFile();
        	if(fujianString!=null & !"".equals(fujianString)){
        		org.jsoup.nodes.Document doc = Jsoup.parse(fujianString);
        		org.jsoup.select.Elements urls = doc.select("a[href]");
        		String urlString,fileName;
        		for(org.jsoup.nodes.Element url:urls){
        			urlString = url.attr("href").trim();
        			fileName = urlString.substring(urlString.lastIndexOf("/")+1);
        			_fujian.addElement("file").setText(fileName);
        		}    
        	}
        }

        writeDocsXML(_docsDocument, toFilePathString);
 
}

public void mkdir(String toFilePathString) {
	
	try{
		if((new File(toFilePathString).isDirectory())){
			FileManage.delFolder(toFilePathString);
//			while((new File(toFilePathString).isDirectory()))
//			{ 
//				synchronized(this) {
//					try{
//						this.wait();
//					}catch(Exception e ) {} 
//				}
//			}  
//			synchronized(this) {
//				try{
//					this.notify();
//				}catch(Exception e ) {} 
//			}
		}
		FileManage.newFolder(toFilePathString);

	}catch(SecurityException e)
	{
	        e.printStackTrace();
	}
}


/**
 * 文件夹打包
 */
public String pack(String toFilePathString, String fujianPathString) {
	
	Date nowDate = new Date();
	String fileName = ToolKit.FormatDate(nowDate).replace("-", "") + "_" + String.valueOf(System.currentTimeMillis()) + ".zip";
	String zipFileUrl = fujianPathString + "\\export\\temp\\" + fileName;
	try {
		zipFile.ZIP(toFilePathString, zipFileUrl);
	} catch (IOException e) {
		fileName="error";
	}
	return fileName;
}

/**
 * 生成cid name对应map
 */
public Map<Integer, String> findExportCidNames(String cidsString) {
	
	String[] cids = cidsString.split(",");
	Map <Integer,String> cidnamesMap = new HashMap<Integer, String>();
	for (String cid:cids){
		Integer icid = Integer.valueOf(cid);
		TjsRoles role=articlesRolesManage.findById(icid);
		cidnamesMap.put(icid, role.getName());
	}
	return cidnamesMap;
}

/**
 * 根据发文日期查找当前用户可查阅的文件
 */
public List<FaWenInfo> selectWenJian(Integer userId, int start, int limit,
		Date startDate, Date endDate) {
	
	String sql =  new String("EXEC exportsearch @first = ?,@limit = ?,@userid = ?,@useridlike = ?,@startDate = ?,@endDate = ?");
	List<FaWenInfo> fawenList = springDao.querySQL(sql, new Object[]{start,limit,userId,"%,"+String.valueOf(userId)+",%",startDate,endDate}, new RowMapper(){

		public Object mapRow(ResultSet arg0, int arg1) throws SQLException {
			if(arg0.getString("id") != null){
				FaWenInfo faWenInfo = new FaWenInfo();
				faWenInfo.setBiaoti(arg0.getString("biaoti"));
				faWenInfo.setWenyear(arg0.getString("wenyear"));
				faWenInfo.setWenhaotype(arg0.getString("wenhaotype"));
				faWenInfo.setFawendatetime(arg0.getDate("fawendatetime"));
				faWenInfo.setWentype(arg0.getString("wentype"));
				faWenInfo.setId(arg0.getString("id"));
				faWenInfo.setTableName(arg0.getString("tablename"));
				faWenInfo.setWenhao(arg0.getInt("wenhao"));
				return faWenInfo;
			}else{
				FaWenInfo faWenInfo = new FaWenInfo();
				faWenInfo.setCount(arg0.getInt("count"));
				return faWenInfo;
			}
		}
	});
	
	return fawenList;
}

public List<TIndexArticles> findDocByIds(String[] idsArray) {
	// TODO Auto-generated method stub
	return null;
}

/**
 * 创建文件XML
 */
public Document createDocsXML(String toFilePathString) {
	// TODO Auto-generated method stub

	 Document _docsDocument = DocumentHelper.createDocument();
	 Element _root = _docsDocument.addElement("documents");
	 return _docsDocument;
}

/**
 *  写XML文件
 */
public void writeDocsXML(Document xmlDocument, String toFilePathString){
	// TODO Auto-generated method stub
	String docurl = toFilePathString + "\\main.xml";
	try{
		OutputFormat format = OutputFormat.createPrettyPrint();
        String filePath = toFilePathString + "\\main.xml";
        FileOutputStream fos = new FileOutputStream(filePath);
        XMLWriter writer = new XMLWriter(fos,format);
        writer.write(xmlDocument);
        writer.close();	
  } catch (Exception e) {
      e.printStackTrace();
  }
}

/**
 * 拷贝行政发文的正文及附件
 */
public Document copyDoc(TXingzhengfawenNeirong doctemp, String toFilePathString, String rootPathString, Document xmlDocument) {
	// TODO Auto-generated method stub
	//拷贝正文
	String sourcepath = rootPathString + "\\documentationflow\\xingzhengfawen\\docs\\";
	String targetpath = toFilePathString + "\\" + doctemp.getId(); 
	FileManage.newFolder(targetpath);
	FileManage.copyFile(sourcepath + doctemp.getDocname(), targetpath + "\\" + doctemp.getDocname());
	
	//向xmldocument中添加元素
	Element _root=xmlDocument.getRootElement();
	Element _docElement = _root.addElement("document");
	_docElement.addElement("uuid").setText(doctemp.getId());
	_docElement.addElement("type").setText(doctemp.getWentype());
	_docElement.addElement("biaoti").setText(doctemp.getBiaoti());
	_docElement.addElement("wenhao").setText(doctemp.getWenhaotype());
	_docElement.addElement("riqi").setText(ToolKit.FormatDate(doctemp.getFawendatetime()));
	Element _fujian = _docElement.addElement("fujian");
	_fujian.addElement("file").setText(doctemp.getDocname());
	//获取附件
	Set<TXingzhengfawenFujian> fujianSet = doctemp.getTXingzhengfawenFujians();
	for (TXingzhengfawenFujian docFujian:fujianSet) {
		//拷贝附件
		FileManage.copyFile(docFujian.getFujianAddress(),targetpath + "\\" + docFujian.getFujianName() );
		//添加xml附件元素
		_fujian.addElement("file").setText(docFujian.getFujianName());
	}
	
	return xmlDocument;
}

/**
 * 拷贝党委发文、纪委、工会、团委文件的正文及附件
 */
public Document copyDoc(TDangweifawenNeirong doctemp, String toFilePathString, String rootPathString, Document xmlDocument) {
	// TODO Auto-generated method stub
	//拷贝正文
	String sourcepath = rootPathString + "\\documentationflow\\dangweifawen\\docs\\";
	String targetpath = toFilePathString + "\\" + doctemp.getId(); 
	FileManage.newFolder(targetpath);
	FileManage.copyFile(sourcepath + doctemp.getDocname(), targetpath + "\\" + doctemp.getDocname());
	
	//向xmldocument中添加元素
	Element _root=xmlDocument.getRootElement();
	Element _docElement = _root.addElement("document");
	_docElement.addElement("uuid").setText(doctemp.getId());
	_docElement.addElement("type").setText(doctemp.getWentype());
	_docElement.addElement("biaoti").setText(doctemp.getBiaoti());
	_docElement.addElement("wenhao").setText(doctemp.getWenhaotype());
	_docElement.addElement("riqi").setText(ToolKit.FormatDate(doctemp.getFawendatetime()));
	Element _fujian = _docElement.addElement("fujian");
	_fujian.addElement("file").setText(doctemp.getDocname());
	//获取附件
	Set<TDangweifawenFujian> fujianSet = doctemp.getTDangweifawenFujians();
	for (TDangweifawenFujian docFujian:fujianSet) {
		//拷贝附件
		FileManage.copyFile(docFujian.getFujianAddress(),targetpath + "\\" + docFujian.getFujianName() );
		//添加xml附件元素
		_fujian.addElement("file").setText(docFujian.getFujianName());
	}
	
	return xmlDocument;
}

/**
 * 根据ids查找党委、纪委、工会、团委文件
 */
public List<TDangweifawenNeirong> findDWDocByIds(String[] idsArray) {
	// TODO Auto-generated method stub
	DetachedCriteria criteria = DetachedCriteria.forClass(TDangweifawenNeirong.class); 
	Disjunction disj = Restrictions.disjunction();
	for (String docid : idsArray) {
	     disj.add(Restrictions.eq("id", docid ));
	}
	criteria.add(disj);
	return  (List<TDangweifawenNeirong>) qbcDao.getCriteria(criteria);
}

/**
 * 根据ids查找行政文件
 */
public List<TXingzhengfawenNeirong> findXZDocByIds(String[] idsArray) {
	// TODO Auto-generated method stub
	DetachedCriteria criteria = DetachedCriteria.forClass(TXingzhengfawenNeirong.class); 
	Disjunction disj = Restrictions.disjunction();
	for (String docid : idsArray) {
	     disj.add(Restrictions.eq("id", docid ));
	}
	criteria.add(disj);
	return  (List<TXingzhengfawenNeirong>) qbcDao.getCriteria(criteria);
}

public TDangweifawenNeirong findDWDocById(String id) {
	// TODO Auto-generated method stub
	DetachedCriteria criteria = DetachedCriteria.forClass(TDangweifawenNeirong.class); 
	criteria.add(Restrictions.eq("id", id ));
	return  (TDangweifawenNeirong) qbcDao.getCriteria(criteria).get(0);
}

public TXingzhengfawenNeirong findXZDocById(String id) {
	// TODO Auto-generated method stub
	DetachedCriteria criteria = DetachedCriteria.forClass(TXingzhengfawenNeirong.class); 
	criteria.add(Restrictions.eq("id", id ));
	return  (TXingzhengfawenNeirong) qbcDao.getCriteria(criteria).get(0);
}


}

